package com.bcxk.common;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * Cookie工具类
 *
 */
public class CookieUtil {

    /**
     * 保存Cookie
     *
     */
    public static void saveCookie(HttpServletResponse resp,String name,String value,int time){
        //创建一个Cookie
        Cookie cookie;
        try {
            cookie = new Cookie(
                    URLEncoder.encode(name, "UTF-8"),
                    URLEncoder.encode(value, "UTF-8"));
            //设置保存路径
            cookie.setPath("/");
            //设置保存时间
            cookie.setMaxAge(time);
            resp.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }


    /**
     * 读取Cookie
     *
     */
    public static String readCookie(HttpServletRequest req,String name){
        Cookie[] cookies = req.getCookies();
        if(null==cookies){
            return null;
        }
        for (Cookie cookie : cookies) {
            try {
                if(name.equals(
                        URLDecoder.decode(cookie.getName(), "UTF-8"))){
                    return URLDecoder.decode(cookie.getValue(), "UTF-8");
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
